package com.swf.seed.security.cert;

import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.MessageDigest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class SecuritySunSigner {
	private static final Logger logger = LoggerFactory
			.getLogger(SecuritySunSigner.class);
	private static String byteArrayToHexString(byte b[]) {
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < b.length; i++)
			sb.append(byteToHexString(b[i]));
		return sb.toString();
	}
	private static String byteToHexString(byte b) {
		int n = b;
		if (n < 0){
			n += 256;
		}
		String hexString = Integer.toHexString(n);
		return hexString.length()==2?hexString:"0"+hexString;
	}

	public static String encode(String origin, String charset,String algorithm) {
		byte[] orginbytes = null ;
		try {
			orginbytes = charset==null?origin.getBytes():origin.getBytes(charset);
		} catch (UnsupportedEncodingException e) {
			logger.error(e.getMessage(), e);
		} 
		return encode(orginbytes,algorithm);
	}
	
	
	public static String encode(byte[] origin,String algorithm) {
		String resultString = "";
		try {
			MessageDigest md = MessageDigest.getInstance(algorithm);
			resultString = byteArrayToHexString(md.digest(origin));
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return resultString;
	}

	private static final String[] hexDigits = { "0", "1", "2", "3", "4", "5",
			"6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };
	
	public static void main(String[] args) {
		System.out.println(encode("ABC".getBytes(), "MD5"));
	}
}
